import {DynamicTable} from "../vxeTable-components/edit-dynamic-table/index.vue.d";
import {deepClone} from "./index";
import {TableItemConfig} from "../vxeTable-components/edit-dynamic-table/TableType";

export interface Point {
  x: number;
  y: number;
}

export class VxeTableUtils {
  /**
   *
   * @param data
   * @param pos 以左上角为 0, 0 开始计算，水平方向为x轴
   * @param table
   * @param addRow 添加行数据
   */
  static async setPastToTable(data: Array<Array<any>>, pos: Point, table: DynamicTable, addRow = {}): Promise<Array<Array<any>>> {
    data = deepClone(data)
    const tableData = table.data as Array<any>
    const tableHead = VxeTableUtils.tableHead2Props(table.tableConfig.tableItems)
    for (let rowIndex = 0; rowIndex < data.length; rowIndex++) {
      const row = data[rowIndex]
      const nowY = rowIndex + pos.y
      if (nowY > tableData.length - 1) {
        await table.addRow(addRow)
      }
      for (let colIndex = 0; colIndex < row.length; colIndex++) {
        const nowX = colIndex + pos.x
        const col = row[colIndex]
        if (nowX <= tableHead.length) {
          const tableCellData = tableData[nowY][tableHead[nowX]]
          tableData[nowY][tableHead[nowX]] = col
          data[rowIndex][colIndex] = tableCellData
        }
      }
    }
    return data
  }

  /**
   * 表头到prop
   * @param tableHead
   */
  static tableHead2Props(tableHead: TableItemConfig[]): string[] {
    const result: string[] = []
    tableHead.forEach(i => {
      if (!i.children) {
        result.push(i.prop)
      }
      if (i.children) {
        result.push(...VxeTableUtils.tableHead2Props(i.children))
      }
    })
    return result
  }
}
